package cn.li.security.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)      //这边开启基于方法的注解
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()      // 下面开始配置权限
                .antMatchers("/admin/**").hasAnyRole("admin")//匹配路径，并要求权限
                .antMatchers("/user/**").hasAnyRole("user")//匹配路径，并要求权限
                .anyRequest().permitAll() //其他的请求都不需要登陆，这里把权限交给了
            .and()                    //security的链式调用
            .formLogin()              //  开启formLogin的filter，用于抓取post /login的表单请求
                .defaultSuccessUrl("/") //这是登陆成功后调用的URL
            .and()
            .logout().permitAll()       //设置退出页面，也可以无权限访问
            .and()
            .httpBasic()                //开启httpbasic的filter
        ;
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    //注入我们指定一个的userDetail
    @Autowired
    public UserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }
}
